package bestTeam.WalkieDoggie.server;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import bestTeam.WalkieDoggie.client.Serializables.UserProfileData;
import bestTeam.WalkieDoggie.client.Serializables.UserRequest;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class EmailServiceImpl extends RemoteServiceServlet {

	String adminEmail = "WalkieDoggieApp@gmail.com"; // insert your admin email address here
	Properties props = new Properties();
	Session session = Session.getDefaultInstance(props, null);

	public static final RequestServiceImpl requestService = new RequestServiceImpl();
	public static FacebookUsersServiceImpl usersService = new FacebookUsersServiceImpl();

	public static HashMap<UserRequest,UserProfileData> requestsOwnersMap = new HashMap<UserRequest, UserProfileData>();

	public static List<UserProfileData> allusers;

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//sendEmail();

		requestsOwnersMap = requestService.getRequestsAndOwners();	

		allusers = usersService.getAllAppUser();

		UserRequest[] requests = (UserRequest[])requestsOwnersMap.keySet().toArray(new UserRequest[0]);
		ArrayList<UserRequest> todayTodo;
		ArrayList<UserRequest> todayMyReq;

		for (UserProfileData user : allusers) {
			if(user!=null && user.getWantDailyEmails()){
				todayTodo = getuserTomorrowToDoRequests(user, requests);
				todayMyReq = getuserTomorrowMyRequests(user, requests);

				if(!todayTodo.isEmpty() || !todayMyReq.isEmpty())
					sendDailyEmail(user, todayTodo, todayMyReq);
			}
		}

	}

	public void sendDailyEmail(UserProfileData user, ArrayList<UserRequest> todayTodo, ArrayList<UserRequest> todayMyReq) {

		//String msgBody = "This is a test email body";

		try {
			Message msg = new MimeMessage(session);
			try {
				msg.setFrom(new InternetAddress(adminEmail, "Administrator"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			try{
				msg.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
			}
			catch(NullPointerException e){
				System.out.println("no email");  
			}

			msg.setSubject("WalkieDoggie Daily Email");

			String body = getHtmlBody(user, todayTodo, todayMyReq);

			msg.setContent(body, "text/html; charset=utf-8");
			Transport.send(msg);

		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}


	}

	public String getHtmlBody(UserProfileData user, ArrayList<UserRequest> todayTodo, ArrayList<UserRequest> todayMyReq) {

		String myCSS = " style=\"color: #335983; font-family:comic sans MS;\"";
		String res="<div>";
		res+="<a href=\"https://walkie-doggie.appspot.com/\" target=\"_blank\"><img src=\"https://walkie-doggie.appspot.com/dailylogo.png\" alt=\"logo\"/></a>";
		res+="<h2"+myCSS+">Hi, "+user.getNickName()+"!</h2>";

		if(requestsOwnersMap!=null){

			res+="<h3"+myCSS+">Your TODOs for Tomorrow:</h3>";

			if(!todayTodo.isEmpty()){
				res+="<ul>";

				for (UserRequest userRequest : todayTodo) {
					res+="<li"+myCSS+">"+userRequest.getTimeFrame()+"\t"+userRequest.getUserName()+"</li>";
				}

				res+="</ul>";
			}

			else{
				res+="<p"+myCSS+">No TODOs.</p>";
			}

			res+="<h3"+myCSS+">Your own Requests for Tomorrow:</h3>";

			if(!todayMyReq.isEmpty()){

				res+="<ul>";

				for (UserRequest userRequest : todayMyReq) {
					res+="<li"+myCSS+">"+userRequest.getTimeFrame();

					String [] volunteers = userRequest.getVolunteers();

					if(volunteers.length>0){
						UserProfileData volunteer;

						res+="<ul>";

						for (int j = 0; j < volunteers.length; j++) {
							volunteer = getUserByID(allusers, volunteers[j]);	

							res+="<li"+myCSS+"> "+volunteer.getNickName()+" rank:"+volunteer.getRanking();
							if(userRequest.getApprovedWalkerID().equals(volunteer.getId()))
								res+=" - approved";
							res+="</li>";
						}

						res+="</ul>";
					}
					else
						res+="<p"+myCSS+"> - No volunteers.</p>";					
				}

			}
			else
				res+="<p"+myCSS+">No requests.</p>";				
		}
		res+="<br/><br/><br/><a href=\"https://walkie-doggie.appspot.com/\" target=\"_blank\""+myCSS+">Visit WalkieDoggie website</a>";

		res+="</div>";

		return res;
	}

	private UserProfileData getUserByID(List<UserProfileData> allusers, String Uid) {

		for (UserProfileData appUser : allusers) {
			if(appUser.getId().equals(Uid))
				return appUser;
		}
		return null;
	}

	private ArrayList<UserRequest> getuserTomorrowMyRequests(UserProfileData user,	UserRequest[] requestsArray) {
		ArrayList<UserRequest> res = new ArrayList<UserRequest>();
		Date start = new Date(); 
		start.setHours(0);
		start.setMinutes(0);
		start.setSeconds(0);

		Calendar cal = Calendar.getInstance();  
		cal.setTime(start);  
		cal.add(Calendar.DAY_OF_YEAR, 1); // <--  
		start = cal.getTime();
		cal.add(Calendar.DAY_OF_YEAR, 1); // <--  
		Date end = cal.getTime();

		for (UserRequest userRequest : requestsArray) {

			if( userRequest.getUserName().equals(user.getNickName())&&
					userRequest.getDate().after(start)&&
					userRequest.getDate().before(end)
					)

				res.add(userRequest);
		}

		return res;
	}

	private ArrayList<UserRequest> getuserTomorrowToDoRequests(UserProfileData user,UserRequest[] requestsArray) {
		ArrayList<UserRequest> res = new ArrayList<UserRequest>();
		Date start = new Date(); 
		start.setHours(0);
		start.setMinutes(0);
		start.setSeconds(0);

		Calendar cal = Calendar.getInstance();  
		cal.setTime(start);  
		cal.add(Calendar.DAY_OF_YEAR, 1); // <--  
		start = cal.getTime();
		cal.add(Calendar.DAY_OF_YEAR, 1); // <--  
		Date end = cal.getTime();

		for (UserRequest userRequest : requestsArray) {

			if( userRequest.getApprovedWalkerID()!=null &&
					userRequest.getApprovedWalkerID().equals(user.getId()) &&
					userRequest.getDate().after(start)&&
					userRequest.getDate().before(end)
					)

				res.add(userRequest);
		}

		return res;
	}

	public void sendEmail(String recipient, String subject, String body) {

		String msgBody = body;

		try {
			Message msg = new MimeMessage(session);
			try {
				msg.setFrom(new InternetAddress(adminEmail, "Administrator"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
			msg.setSubject(subject);
			msg.setContent(msgBody,"text/html; charset=utf-8");  //TIP: use msg.setContent to send an HTML formatted email
			Transport.send(msg);

		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}

	}

	public String sendEmailWithImage(String recipient, String subject, String body ,byte[] file) {

		try {
			Message msg = new MimeMessage(session);
			try {
				msg.setFrom(new InternetAddress(adminEmail, "Administrator"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
			msg.setSubject(subject);

			MimeBodyPart textPart = new MimeBodyPart();
//			textPart.setContent("<h1>Check attachment</h1>", "text/html");
			textPart.setText(body);
			
			MimeBodyPart attachFilePart = new MimeBodyPart();
			DataSource fds = new ByteArrayDataSource(file,"image/jpeg");
			attachFilePart.setDataHandler(new DataHandler(fds));
			attachFilePart.setFileName("your_dog.jpg");

			Multipart mp = new MimeMultipart();
			mp.addBodyPart(textPart);
			mp.addBodyPart(attachFilePart);

			msg.setContent(mp);

			Transport.send(msg);    

			return "email sent";

			//			
			//			// Create the message part 
			//			BodyPart messageBodyPart = new MimeBodyPart();
			//
			//			// Fill the message
			//			//messageBodyPart.setContent(body,"text/html; charset=utf-8");
			//			messageBodyPart.setContent("<p>omer</p>", "text/html");
			//			Multipart multipart = new MimeMultipart();
			//			multipart.addBodyPart(messageBodyPart);
			//
			//			// Part two is attachment
			//			BodyPart attachment = new MimeBodyPart();
			//			String filename = "your_dog_photo.jpg";
			//			DataSource source = new ByteArrayDataSource(file, "image/jpeg");
			//			attachment.setDataHandler(new DataHandler(source));
			//			attachment.setFileName(filename);
			//			multipart.addBodyPart(attachment);
			//
			//			// Put parts in message
			//			msg.setContent(multipart);
			//
			//			// Send the message
			//			Transport.send(msg);



		} catch (AddressException e) {
			e.printStackTrace();
			return e.getMessage();
		} catch (MessagingException e) {
			e.printStackTrace();
			return e.getMessage();
		}



	}

	public void sendEmail() {

		String msgBody = "This is a test email body";

		try {
			Message msg = new MimeMessage(session);
			try {
				msg.setFrom(new InternetAddress(adminEmail, "Administrator"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
					"shachafby@gmail.com"));
			msg.setSubject("This is a test email subject");
			msg.setText(msgBody);  //TIP: use msg.setContent to send an HTML formatted email
			Transport.send(msg);

		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}

	}

	public void IndSendDailyEmail(UserProfileData user){
		requestsOwnersMap = requestService.getRequestsAndOwners();	

		UserRequest[] requests = (UserRequest[])requestsOwnersMap.keySet().toArray(new UserRequest[0]);
		ArrayList<UserRequest> todayTodo;
		ArrayList<UserRequest> todayMyReq;
		todayMyReq = getuserTomorrowMyRequests(user, requests);
		todayTodo = getuserTomorrowToDoRequests(user, requests);

		sendDailyEmail(user, todayTodo, todayMyReq);
	}

}